package com.fadadianqi.logistics.admin.email;

import com.fadadianqi.logistics.admin.StatisticsService;
import com.fadadianqi.logistics.admin.controller.DateTimeHelper;
import com.fadadianqi.commons.ConfigHelper;
import com.fadadianqi.logistics.customer.model.Customer;
import com.fadadianqi.logistics.customer.model.Town;
import com.fadadianqi.logistics.customer.model.Village;
import com.fadadianqi.logistics.customer.service.CustomerService;
import com.fadadianqi.goods.model.Brand;
import com.fadadianqi.goods.model.Category;
import com.fadadianqi.goods.service.GoodsService;
import com.fadadianqi.logistics.sell.model.Bill;
import com.fadadianqi.logistics.sell.model.Goods;
import com.fadadianqi.logistics.sell.model.InOut;
import com.fadadianqi.logistics.sell.service.BillService;
import com.fadadianqi.logistics.sell.service.InOutService;
import com.yeqiangwei.commons.mail.MailConfig;
import com.yeqiangwei.commons.mail.MailEntity;
import com.yeqiangwei.commons.mail.MailService;
import com.yeqiangwei.commons.mail.exception.MailException;
import com.yeqiangwei.commons.util.DateTimeUtils;
import com.yeqiangwei.commons.util.Pagination;
import com.yeqiangwei.commons.util.ValidatorHelper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 备份昨天数据到邮箱
 *
 * @author aroot
 */
@Service
public class EmailService {

    private static final Log log = LogFactory.getLog(EmailService.class);

    private String yestoday = null;
    private String latest = null;

    /**
     * @throws MailException
     * @throws ParseException
     */
    public void job() throws MailException, ParseException {
        latest = ConfigHelper.getString("admin.em.lt", null); // 最后一次邮件发送时间
        long _yestoday = DateTimeUtils.nDaysAfterTime(-1);
        yestoday = DateTimeUtils.format(_yestoday, DateTimeUtils.FMT_YYYY_MM_DD);
        log.debug("#job# latest:" + latest + ", yestoday:" + yestoday);
        if (!yestoday.equalsIgnoreCase(latest)) {
            send();
            ConfigHelper.set("admin.em.lt", yestoday);
        }
    }

    private void send() throws MailException, ParseException {
        String _emails = ConfigHelper.getString("admin.em.ad");
        String smtp_fm = ConfigHelper.getString("admin.smtp.fm");
        if (ValidatorHelper.isEmpty(_emails)) {
            return;
        }
        MailConfig config = new MailConfig();
        config(config);
        log.debug("[MailConfig] " + config.toString());
        MailService mailService = new MailService();
        String[] emails = _emails.split(",");
        String subject = getSubject();
        String content = getContent();
        for (String to : emails) {
            MailEntity entity = new MailEntity();
            entity.setFrom(smtp_fm);
            entity.setTo(to);
            entity.setSender(ConfigHelper.getString("admin.site.name"));
            entity.setSubject(subject);
            entity.setHtmlText(content);
            mailService.sendMail(mailService.getSession(config), entity);
            log.debug(entity.toString());
        }
    }

    private String getSubject() {
        return yestoday;
    }

    private String getContent() throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date _yestoday = sdf.parse(yestoday);
        Date s = DateTimeHelper.getOfDayStart(_yestoday);
        Date e = DateTimeHelper.getOfDayEnd(_yestoday);
        StringBuilder sb = new StringBuilder();
        double cost = billService.sumCostBetween(s, e);
        double realpayables = billService.sumRealPayablesBetween(s, e);
        double inoutMoney = inOutService.sumMoneyBetween(s, e); //流水帐
        //int total = billService.countBetween(s, e);
        sb.append("<h3>");
        sb.append(yestoday);
        sb.append("销售数据备份</strong>：");
        sb.append("<h3/>");
        sb.append("<strong>销售金额</strong>：");
        sb.append(realpayables);
        sb.append("<br/>");
        sb.append("<strong>销售成本</strong>：");
        sb.append(cost);
        sb.append("<br/>");
        sb.append("<strong>当日利润</strong>：");
        sb.append(realpayables - cost);
        sb.append("<br/>");
        sb.append("<strong>当日流水</strong>：");
        sb.append(inoutMoney);
        sb.append("<br/><br/>");
        Pagination pagination = new Pagination(1, 1000);
        List<InOut> inOutList = inOutService.findBetween(s, e, pagination);
        if (ValidatorHelper.isNotEmpty(inOutList)) {
            sb.append("<h3>流水详细</h3>");
            sb.append("<ol>");
            for (InOut item : inOutList) {
                sb.append("<li>");
                sb.append(item.getMemo());
                sb.append("：");
                sb.append(item.getMoney());
                sb.append("</li>");
            }
            sb.append("</ol>");
        }
        List<Bill> bills = billService.between(s, e, pagination);
        if (ValidatorHelper.isNotEmpty(bills)) {
            sb.append("<h3>销售详细</h3>");
            sb.append("<table><tr>");
            sb.append("<th>商品</th>");
            sb.append("<th>售价</th>");
            sb.append("<th>顾客</th>");
            sb.append("<th>销售时间</th>");
            sb.append("</tr>");
            for (Bill bill : bills) {
                List<Goods> goodsList = billService.findGoodsByBillId(bill.getId());
                if (ValidatorHelper.isEmpty(goodsList)) {
                    continue;
                }
                sb.append("<tr>");
                sb.append("<td><ol>");
                for (Goods _goods : goodsList) {
                    Category category = goodsService.getCategoryById(_goods.getCategoryId());
                    Brand brand = goodsService.getBrandById(_goods.getBrandId());
                    com.fadadianqi.goods.model.Goods goods = goodsService.getGoodsById(_goods.getGoodsId());
                    sb.append("<li>");
                    sb.append(brand.getName());
                    sb.append(category.getName());
                    sb.append(goods.getName());
                    sb.append(" (");
                    sb.append(_goods.getUnitPrice());
                    sb.append(")");
                    sb.append("</li>");
                }
                sb.append("</ol></td>");
                sb.append("<td>");
                sb.append(bill.getRealPayables());
                sb.append("</td>");
                sb.append("<td>");
                Customer customer = customerService.getById(bill.getCustomerId());
                if (customer != null) {
                    Town town = customerService.getTownById(customer.getTownId());
                    if (town != null) {
                        sb.append(town.getName());
                        sb.append(" ");
                    }
                    Village village = customerService.getVillageById(customer.getVillageId());
                    if (village != null) {
                        sb.append(village.getName());
                        sb.append(" ");
                    }
                    sb.append(customer.getName());
                    sb.append("<br/>");
                    sb.append(customer.getMobile());
                }
                sb.append("</td>");
                sb.append("<td>");
                sb.append(DateTimeUtils.format(bill.getAddTime().getTime()
                        , DateTimeUtils.FMT_YYYY_MM_DD_HH_MM_SS));
                sb.append("</td>");
                sb.append("</tr>");
            }
            sb.append("</table>");
        }
        //
        int thisYear = DateTimeUtils.getCurrentYear();
        Double totalInventory = statisticsService.totalInventory(); //库存价值
        //Double totalPurchase = statisticsService.totalPurchase(); //库存成本
        Double totalSales = statisticsService.totalSales(thisYear);
        Double totalCost = statisticsService.totalCost(thisYear);
        Double money = statisticsService.totalInOutMoney(thisYear);
        sb.append("<p>");
        sb.append(thisYear);
        sb.append("年度 库存总额:");
        sb.append(totalInventory);
        sb.append(", 销售总额:");
        sb.append(totalSales);
        sb.append(", 毛利润:");
        sb.append(totalSales - totalCost);
        sb.append(", 流水记录:");
        sb.append(money);
        sb.append(", 净利润:");
        sb.append(totalSales - totalCost + money);
        sb.append("</p>");
        return sb.toString();
    }


    private void config(MailConfig config) {
        //MailConfig config = new MailConfig();
        String smtp_ad = ConfigHelper.getString("admin.smtp.ad");
        String smtp_pw = ConfigHelper.getString("admin.smtp.pw");
        String smtp_port = ConfigHelper.getString("admin.smtp.port");
        String smtp_id = ConfigHelper.getString("admin.smtp.id");
        Boolean smtp_ssl = ConfigHelper.getBoolean("admin.smtp.ssl");
        config.setSmtpAccount(smtp_id);
        config.setSmtpPassword(smtp_pw);
        config.setSmtpNeedPassword(true);
        config.setSmtpNeedSSL(smtp_ssl);
        config.setSmtpPort(smtp_port);
        config.setSmtpServer(smtp_ad);
    }

    @Autowired
    private CustomerService customerService;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private BillService billService;

    @Autowired
    private InOutService inOutService;

    @Autowired
    private StatisticsService statisticsService;

}
